import React, { useState, useMemo, useEffect } from "react";
import { Select, Input, Button, Icon, Form } from "antd";
import styles from "./TemplateItem.less";

const { Option } = Select;
const { TextArea } = Input;

function TemplateItem(props) {
  const { form, contentArr, selectItem } = props;
  const { getFieldDecorator, setFieldsValue, getFieldValue } = form;
  const [templateArr, setTemplateArr] = useState([]); // 存放模板内容
  const type = getFieldValue("type");
  const title = getFieldValue("title");
  const itemStyle = { width: 116 };

  // 维护一个独立id
  const createId = () => {
    // 私有变量
    let selfId = 0;
    return Object.create(null, {
      get: {
        value: () => {
          selfId += 1;
          return selfId;
        }
      }
    });
  };
  const itemId = useMemo(() => createId(), []);
  useEffect(() => {
    const temp = [...contentArr].map(item => ({ ...item, id: itemId.get() }));
    setTemplateArr(temp);
  }, [contentArr]);

  // 将templateArr转换成对应的String
  const getTextAreaValue = () => {
    const res = templateArr.reduce(
      (prev, next) => {
        let temp;
        switch (next.type) {
          case "input":
            temp = next.value;
            break;
          case "select":
            temp = next.value ? `{${next.value}}` : "";
            break;
          case "enter":
            temp = "\n";
            break;
          default:
            temp = "";
        }
        return {
          displayContent: prev.displayContent + temp,
          content: `${prev.content + temp}#`
        };
      },
      {
        content: "",
        displayContent: `${title ? `${title}\n` : ""}`
      }
    );
    return res;
  };
  // 数据双向绑定
  const handleChange = (value, index) => {
    const temp = [...templateArr];
    temp[index].value = value;
    setTemplateArr(temp);
  };
  useEffect(() => {
    setFieldsValue({
      content: getTextAreaValue().content,
      displayContent: getTextAreaValue().displayContent
    });
  }, [templateArr, title, type]);
  // 渲染一个下拉框
  const renderSelect = index => (
    <Select
      style={itemStyle}
      // 绑定对应value
      value={templateArr[index].value}
      onChange={value => handleChange(value, index)}
    >
      {selectItem.map((item, i) => (
        <Option value={item.value} key={i}>
          {item.value}
        </Option>
      ))}
    </Select>
  );
  // 渲染一个输入框
  const renderInput = index => (
    <Input
      style={itemStyle}
      value={templateArr[index].value}
      onChange={e => handleChange(e.target.value, index)}
    />
  );
  // 映射类型与其对应的组件
  const itemMap = {
    input: renderInput,
    select: renderSelect,
    enter: () => <div className={styles.enter}>换行符</div>
  };

  const add = itemType => {
    const temp = [
      ...templateArr,
      {
        type: itemType,
        id: itemId.get(),
        value: ""
      }
    ];
    setTemplateArr(temp);
  };
  const remove = id => {
    const temp = [...templateArr].filter(item => item.id !== id);
    setTemplateArr(temp);
  };

  return (
    <React.Fragment>
      <div className={styles.item}>
        <div
          style={{ visibility: `${type === 1 ? "hidden" : "visible"}` }}
          className={styles.itemName}
        >
          模板内容
        </div>
        <ul className={styles.itemArea}>
          {templateArr.map((item, index) => (
            <li key={item.id}>
              {itemMap[item.type](index)}
              <Icon
                type="close-circle"
                theme="filled"
                style={{ color: "red", margin: "0 12px" }}
                onClick={() => remove(item.id)}
              />
            </li>
          ))}
          <div style={{ clear: "both" }}>
            <li>
              <Button style={itemStyle} onClick={() => add("input")}>
                +文本
              </Button>
            </li>
            <li>
              <Button
                style={{ ...itemStyle, margin: "0 9px" }}
                onClick={() => add("select")}
              >
                +变量
              </Button>
            </li>
            <li>
              <Button style={itemStyle} onClick={() => add("enter")}>
                +换行符
              </Button>
            </li>
          </div>
        </ul>
      </div>

      <Form.Item
        labelCol={{ span: 3 }}
        wrapperCol={{ span: 21 }}
        label="模板预览"
      >
        {getFieldDecorator("displayContent", {
          rules: [
            {
              validator: async (rule, value) => {
                if (!value) throw new Error("请输入模板内容");
              }
            }
          ]
        })(
          <TextArea autoSize={{ minRows: 5 }} disabled style={{ width: 800 }} />
        )}
      </Form.Item>
      <Form.Item style={{ display: "none" }}>
        {getFieldDecorator("content")(
          <TextArea autoSize={{ minRows: 5 }} disabled style={{ width: 800 }} />
        )}
      </Form.Item>
    </React.Fragment>
  );
}

export default TemplateItem;
